package com.googlecode.imanager.client.value.el;

import java.io.Serializable;
import java.util.Date;

import com.googlecode.imanager.client.value.HasValue;
import com.googlecode.imanager.client.value.HasValueType;
import com.googlecode.imanager.client.value.ValueType;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public abstract class Expression 
           implements Serializable, HasValueType, HasValue {

    private static final long serialVersionUID = 1L;
    
    protected static final Expression[] EMPTY_EXPRESSION_ARRAY = new Expression[0];

    public ValueType getValueType() {
        return ValueType.DEFAULT;
    }

    public abstract Object getValue();
    
    public abstract Expression[] getSubExpressions();
    
    @Override
    public final String toString(){
        return convertToString(getValue());
    }
    
    public final double toDouble(){
        return convertToDouble(getValue());
    }
    
    protected double convertToDouble(Object o) {
        if (o != null){
            if (o instanceof Expression){
                return convertToDouble(((Expression) o).getValue());
            }
            
            if (o instanceof Number){
                return ((Number) o).doubleValue();
            }
            
            if (o instanceof Boolean){
                return ((Boolean) o).booleanValue() ? 1 : 0;
            }
            
            if (o instanceof Date){
                return ((Date) o).getTime();
            }

            String str = o.toString();
            try {
                return Double.parseDouble(str);
                
            } catch (NumberFormatException e){
                return 0;
            }
        }
        return 0;
    }

    protected String convertToString(Object o) {
        return o == null ? "" : o.toString();
    }

}
